package com.util;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;

/**
 * 支付宝付款qrcode例子
 *
 * @author admin
 * @date 2023/06/19
 */
public class AlipayQRCodePayment {
    /**
     * 支付宝门户url
     */
    private static final String ALIPAY_GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    /**
     * 应用程序id
     */
    private static final String APP_ID = "9021000122681154";
    /**
     * 私钥
     */
    private static final String PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCR98Di/v1WAhUEVyX+RlCA01kZEQ0WqdLEduUgrp3Exh53p0tgo8otOGCKruA3mjnOHILX8eAefAd10ANPYuM6BCRhyhrCj8zixb3lQeus8OQe2dhMrKZSm3TJJElAV+K4ZiFb8ZbaAwFfOsj6RC0TMk0WptcAqL/Y9Pa7EVR44Xmgl+e91R+sWXxEj84YzY2vrW9o15+NS8bO5RDpuS9UxOT/0GZFaR+3+PaFVd95nxLr8gPo8bccv51WRMfMwKREZcXIS3fs04mkiYtQx69gvFKsSPnVmOiJi7XYR4cspQIvGEOkB45qUlc23b/up2tplzpdBeiuDtuzbgUA5vIxAgMBAAECggEBAItwj9TJHh1hk843qlXDufe27nBht40k4fFIWw3jgVeOo2BOclV5YhPcvWz+LbcwH3RkDCJaL20vsri6486cetDbUB4SwYmHcYRYvlUZqhflbyaBmH12mNRlKSVVApzy1+Sru8ZnfWH6aP8d2wwowJ6L+NRgwRciHVMWf/SoU3e9C9CiGC8VOESXfrna8W2S1te3ufGHUk+2bsdWX56nf84HR0U/U3zZ1zFtbp67H5g6rJOKVr3eyq0x4470mCBHg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5SxU8u3SdruMjZ6Npqj4mbgMy3XMLyfmgPXqF4js3FxbBGp5Em0IJk/vr3pRrcmf4ouJoC/ElvJDxhdY5RsFXN5BCgfr10gwEnNgQdXc/z9IBpJgZFqD4+ZELfMEY1Pn+gesOi26GkApoDckx+/0I7zfnMGOSH4+Glcut2jcU4rIyfnfu+Zgt8RUAv3DDEbKbklyqM3LCCQZTy4+BU9VpCQ/K50kywwv7AVKONjLKkL15Wm5iPEq4jxsftmZ8LblO3/cvB2Ia4CFF+PqNu8f5GGM9RM3ZM3nLniYuevKkBwgDg0FBKXv1d6BOZEDM3gXiQIDAQAB";

    private static final AlipayClient alipayClient = new DefaultAlipayClient(ALIPAY_GATEWAY_URL, APP_ID, PRIVATE_KEY, "json", "UTF-8", ALIPAY_PUBLIC_KEY, "RSA2");

    public static String payOrder(AlipayTradePayModel model) throws AlipayApiException {
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setBizModel(model);
        AlipayTradePrecreateResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            return response.getQrCode();
        } else {
            throw new AlipayApiException("预创建请求失败：" + response.getSubMsg());
        }
    }

    public static AlipayTradeQueryResponse queryOrder(AlipayTradeQueryModel model) throws AlipayApiException {
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizModel(model);
        return alipayClient.execute(request);
    }
}
